/**
 * @Author: Cui Ruichen
 * @Date: 2023-03-23 16:50:40
 * @LastEditors: Cui Ruichen
 * @LastEditTime: 2023-03-23 16:50:40
 * @Description: router全局配置，如有必要可分文件抽离，其中asyncRoutes只有在intelligence模式下才会用到
 */
import { Router, RouteRecordRaw, createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layouts/index.vue'

// 静态路由
const constantRoutes: RouteRecordRaw[] = [
  // 默认首页重定向
  {
    path: '/',
    name: 'Root',
    redirect: '/home',
    component: Layout,
    meta: { name: '首页' },
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('@/views/home/index.vue'),
        meta: { name: '首页' },
      },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { name: '登陆' },
  },
  {
    path: '/403',
    name: '403',
    component: () => import('@/views/error-page/403.vue'),
    meta: { name: '403' },
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error-page/404.vue'),
    meta: { name: '404' },
  },
]

// 动态页面
const asyncRoutes: RouteRecordRaw[] = [
  {
    path: '/setting',
    name: 'Setting',
    component: () => import('@/views/setting/index.vue'),
    meta: {
      name: '设置',
    },
  },
  {
    path: '/test',
    name: 'Test',
    component: () => import('@/views/test/index.vue'),
    meta: {
      name: '测试页',
    },
    children: [
      {
        path: '/test1',
        name: 'Test1',
        component: () => import('@/views/test/test1.vue'),
        meta: {
          name: '测试页1',
        },
      },
      {
        path: '/test2',
        name: 'Test2',
        component: () => import('@/views/test/test2.vue'),
        meta: {
          name: '测试页2',
        },
      },
    ],
  },
]

const routes = constantRoutes

/* 创建路由实例 */
const router: Router = createRouter({
  history: createWebHistory(''),
  // "hash",
  routes,
})

asyncRoutes.forEach((item) => {
  router.addRoute(item)
})

/* 路由白名单 */
const whiteList = ['/login']

/**
 * @description: 全局路由守卫
 * @author Cui Ruichen
 * @date 2023-03-24 14:06:23
 */
router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.path)) {
    //若要跳转的页面是白名单内的页面，则直接跳转
    next()
  } else {
    //若要跳转的页面是内部页面
    const token = localStorage.getItem('token') //获取本地存储的token值
    if (token === null || token === '') {
      //若token为空则验证不成功，跳转到登录页面
      next('/login')
    } else {
      //不为空则验证成功
      next()
    }
  }
})

/** 不参与菜单的路由地址 */
export const constantRoutesPath = Object.keys(constantRoutes).map((v: string) => {
  return constantRoutes[v].path
})

export default router
